<?php

namespace App\Http\Controllers\Goods;

use App\Common\Result;
use App\Http\Controllers\Controller;
use App\Models\Inquiry\InquirySheet;
use App\Service\Goods\GoodsCommentService;
use App\Service\Goods\GoodsService;
use App\Service\Indent\OrderService;
use App\Service\Inquiry\InquiryService;
use App\Service\ServiceLog;
use App\Service\Work\BestWorksService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class GoodsController extends Controller
{
    /**
     * 发布商品
     */
    public function putGoods(Request $request)
    {
        $uid = $request->input('uid');
        $contents = $request->input('contents');
        $photos = $request->input('pictures');
        $price = $request->input('price');
        $title = $request->input('title');
        $article_class = $request->input('aclass');
        $key_word = $request->input('keyword');
        $location = $request->input('location');
        $lon = $request->input('lon');
        $lat = $request->input('lat');

        $qiniu_config = config("qiniu.qiniu");


        //处理照片url
        if(!empty($photos)){
            $photos = json_decode($photos);
            foreach($photos as $key=>$value){
                $photos[$key] = $qiniu_config['imgPath'].$value;
            }
            //处理缩略图问题
            if(count($photos) >3){
                $thumb = array_slice($photos, 0, 3);
                $thumb = json_encode($thumb);
            }else{
                $thumb = json_encode($photos);
            }

            $photos = json_encode($photos);

        }else{
            $thumb = '';
        }

        $data = array(
            'author_uid' => $uid,
            'content' => $contents,
            'photo' => $photos,
            'price' => $price,
            'title' => $title,
            'thumb' => $thumb,
            'status' => 1,
            'cid' => 1,
            'article_class' => $article_class,
            'create_time' => date("Y-m-d H:i:s"),
            'publish_time' => date("Y-m-d H:i:s"),
            'key_word' => $key_word,
            'buy_class' => 2,
            'location' => $location,
            'lon' => $lon,
            'lat' => $lat
        );

        $res = BestWorksService::createArticle($data);
        try {
            if ($res) {
                //加入redis缓存
                Redis::sadd('workslistids', "articles:{$res}");
                Redis::hmset("articles:{$res}",
                    "author_uid", "{$uid}",
                    "content", "{$title}",
                    "photos", "{$thumb}",
                    "location", "{$location}",
                    "read_num", 0,
                    "comment_num", 0,
                    "share_num", 0,
                    "class", 2,  //2商品
                    "id","{$res}",
                    "aclass","{$article_class}",
                    "price","{$price}",
                    "created","{$data['create_time']}");

                Result::msg('0', 'success', $data);
            } else {
                Result::msg('-11', 'error', '更新失败');
            }
        }catch (\Exception $e){
            ServiceLog::record("debug.txt",$e->getMessage(),'error');
            Result::msg('-888','error','网络出错了');
        }
    }

    /**
     * 商品详情
     */
    public function goodsDetail(Request $request)
    {
        $goods_id = $request->goods_id;

        if(!$goods_id){
            Result::msg('-43','error','商品id为空');
        }

        $goods_info = GoodsService::getGoodsIdInfo($goods_id);

        if(!$goods_info || $goods_info['is_up'] === 0){
            Result::msg('-44','error','商品已经下架');
        }
        $label_name = \DB::table('lsj_label')->where('id',$goods_info->label_id)->first();

        $goods_info->photos = json_decode($goods_info->photos,true);

        $comment_info = GoodsCommentService::getMoreComments($goods_id);

        $goods_info->content = "<div style='width: 100%;margin: 0 auto;text-align:center;'>".htmlspecialchars_decode($goods_info->content)."</div>";

        $result = [
            'goods_info' => $goods_info,
            'comment_info' => $comment_info,
            'comment_num' => GoodsCommentService::getCommentsNum($goods_id),
            'label_name' => $label_name
        ];

        Result::msg('0','success',$result);
    }

    /**
     * 商品评价列表
     */
    public function goodsCommentList(Request $request)
    {
        $goods_id = $request->goods_id;
        $page = $request->page;

        $offset = ($page-1)*10;

        $result = GoodsCommentService::getCommentList($goods_id,$offset);

        Result::msg('0','success',$result);
    }

    /**
     * 商品评价
     */
    public function commentGoods(Request $request)
    {
//        $goods_id = $request->goods_id;
        $content = $request->message;
        $uid = $request->uid;
        $order_id = $request->order_id;
        $photos = $request->pictures;



        //评论权限
        $order_info = OrderService::getOrderArray([
            'order_id' => $order_id,
            'uid' => $uid
        ]);

        if(!isset($order_info['status']) || $order_info['status'] != 3){
            Result::msg('-54','error','订单状态出错');
        }

        //订单商品
        $order_goods_info = InquirySheet::where('id',$order_info->inquiry_sheet_id)->first();

        if(!$order_goods_info){
            Result::msg('-55','error','订单商品不存在');
        }

//        if(!isset($order_goods_info['status']) || $order_goods_info['status'] != 1){
//            Result::msg('-54','error','订单状态出错');
//        }

        //处理照片url
        if(isset($photos) && !empty($photos)){
            $qiniu_config = config("qiniu.qiniu");
            $photos = json_decode($photos);
            foreach($photos as $key=>$value){
                $photos[$key] = $qiniu_config['imgPath'].$value;
            }
            $photos = json_encode($photos);
        }else{
            $photos = '';
        }

        \DB::beginTransaction();
        try{
            $data = [];
//            foreach($order_goods_info as $key=>$goods){
//                $data[$key]['uid'] = $uid;
//                $data[$key]['goods_id'] = $goods['goods_id'];
//                $data[$key]['content'] = $content;
//                $data[$key]['photos'] = $photos;
//                $data[$key]['created_at'] = date('Y-m-d H:i:s',time());
//            }
            $data['uid'] = $uid;
            $data['goods_id'] = $order_goods_info->goods_id;
            $data['content'] = $content;
            $data['photos'] = $photos;
            $data['comment_status'] = $request->comment_status;
            $data['created_at'] = date('Y-m-d H:i:s',time());
            GoodsCommentService::commentGoods($data);
            OrderService::changeOrder($order_id,['status'=>4]);
            \DB::commit();
            Result::msg('0','success',[]);
        }catch (\Exception $e){
            \DB::rollback();
            Result::msg('-11','error','更新失败');
        }
    }
}